<script>
import { merge, omit, isString } from "lodash";
import BaseForm from "../Form/form.vue";
import siteMixin from "../../siteMixin.js";
import FormButton from "../Form/button.vue";
export default {
  mixins: [siteMixin],
  data() {
    return {
      formData: {},
      loading: false,
      loading2: false,
      loading3: false,
    };
  },
  computed: {
    formOptions() {
      const columns =
        this.dialogOptions.columns?.map?.((column) => {
          return merge(
            {
              context: this, // 使得column的render可以绑定外部上下文
            },
            column
          );
        }) || [];
      // if (columns.length) {
      //   // 最后一行后面是按钮，换行
      //   columns[columns.length - 1].br = true;
      // }
      return merge(
        {
          height: "500px",
          width: "500px",
          class: "", // body 样式类
          scroll: true,
          unlock: false, // 解锁管理员
          submit: true, // 通过
          reject: false, // 拒绝
          cancel: true, // 取消
          unlockTitle: $AONE_LAN.unlock,
          submitTitle: $AONE_LAN.sure,
          rejectTitle: $AONE_LAN.reject,
          cancelTitle: $AONE_LAN.cancel,
          isDialog: true,
          labelWidth: this.isCn ? "100px" : "120px", // 中英宽度不同
        },
        {
          columns,
          ...omit(this.dialogOptions, ["columns"]),
        }
      );
    },
    classNames() {
      const classNames = ["Dialog"];
      if (this.dialogOptions.scroll !== false) {
        classNames.push("Dialog-form-scroll");
      }
      return classNames.join(" ");
    },
  },
  provide() {
    return {
      context: {
        onSubmit: this._onSubmit,
        onReject: this._onReject,
        onCancel: this._onCancel,
      },
    };
  },
  watch: {
    formData: {
      deep: true,
      handler() {
        if (!this.$refs.form?.formData) return;
        for (let key in this.formData) {
          this.$refs.form.formData[key] = this.formData[key];
        }
      },
    },
  },
  methods: {
    _onClose() {
      this._onCancel();
    },
    async _onSubmit() {
      // 弹窗提供onSubmit方法
      this.loading = true;
      if (this.onSubmit) {
        await this.onSubmit(
          this._formatValue(this.formOptions.columns, this.formData)
        )
          .then(
            (bl) => {
              // if (bl !== false) {
              //   // 关闭弹窗
              //   this.closeAndDestroy();
              // }
            },
            (error) => {
              if (isString(error)) {
                this.$alert({ center: error, type: "fail" });
              }
            }
          )
          .finally(() => {
            this.loading = false;
          });
      }
    },
    async _onReject() {
      // 弹窗提供onReject方法
      this.loading2 = true;
      if (this.onReject) {
        await this.onReject(
          this._formatValue(this.formOptions.columns, this.formData)
        )
          .then(
            (bl) => {
              // if (bl !== false) {
              //   // 关闭弹窗
              //   this.closeAndDestroy();
              // }
            },
            (error) => {
              if (isString(error)) {
                this.$alert({ center: error, type: "fail" });
              }
            }
          )
          .finally(() => {
            this.loading2 = false;
          });
      }
    },
    /**
     * 调用可手动表单验证
     */
    async checkValidateForm() {
      return await this.$refs.form.checkValidateForm();
    },
    _onUnlock() {
      this.onUnlock?.(this.formData);
    },
    _onCancel() {
      const isClose = this.onCancel?.(this.formData);
      // 如果强制返回了false，则不关闭
      if (isClose !== false) {
        this.closeAndDestroy();
      }
    },
    _onFormDataUpdate(formData) {
      for (let key in formData) {
        this.$set(this.formData, key, formData[key]);
      }
    },
    renderFooter() {
      const btns = [];
      if (this.formOptions.unlock) {
        btns.push(
          <FormButton
            type=""
            size="small"
            class="aoneui-dialog-footer-unlock"
            loading={this.loading3}
            label={this.formOptions.unlockTitle}
            onClick={() => this._onUnlock?.()}
          />
        );
      }
      if (this.formOptions.submit) {
        btns.push(
          <FormButton
            type="primary"
            size="small"
            class="aoneui-dialog-footer-search"
            loading={this.loading}
            label={this.formOptions.submitTitle}
            onClick={() => this.$refs.form?.onSubmit?.()}
          />
        );
      }
      if (this.formOptions.reject) {
        btns.push(
          <FormButton
            type="warning"
            size="small"
            class="aoneui-dialog-footer-reject"
            loading={this.loading2}
            label={this.formOptions.rejectTitle}
            onClick={() => this.$refs.form?.onReject?.()}
          />
        );
      }
      if (this.formOptions.cancel) {
        btns.push(
          <FormButton
            label={this.formOptions.cancelTitle}
            type=""
            class="aoneui-dialog-footer-cancel"
            size="small"
            onClick={this._onCancel}
          />
        );
      }
      return btns;
    },
  },
  render() {
    return (
      <el-dialog
        visible={true}
        class="aoneui-dialog"
        title={this.formOptions.title}
        before-close={this._onClose}
        width={`${this.formOptions.width}`}
        close-on-click-modal={false}
        append-to-body
      >
        <div
          style={"overflow:auto;max-height:" + this.formOptions.height}
          class={["aoneui-dialog-scroll-wrapper", this.formOptions.class]}
        >
          <BaseForm
            ref="form"
            class="aoneui-dialog-form"
            formOptions={this.formOptions}
            onFormDataUpdate={this._onFormDataUpdate}
          />
        </div>
        <div slot="footer" class="aoneui-dialog-footer">
          {this.renderFooter()}
        </div>
      </el-dialog>
    );
  },
};
</script>
<style lang="scss" scoped>
.aoneui-dialog {
  .aoneui-dialog-form {
    padding: 15px 15px 0 15px;
  }
  /deep/ {
    .el-dialog__body {
      padding: 0;
    }
    .aone-form-item-comtype {
      width: 90%;
    }
    .aone-page-header {
      display: none;
    }
  }
}
// .aoneui-dialog-scroll-wrapper::-webkit-scrollbar {
//   width: 7px;
//   height: 10px;
//   background-color: transparent;
// }
// .aoneui-dialog-scroll-wrapper::-webkit-scrollbar-thumb {
//   display: block;
//   border-radius: 5px;
//   width: 5px;
//   background-color: #6a6b6d4d;
// }
.aoneui-dialog-footer {
  text-align: center;
}
</style>
